//========================================================================================
//  
//  $File:
//  
//  Owner: Adobe Developer Technologies
//  
//  $Author: alokumar $
//  
//  $DateTime: 2011/04/01 11:22:15 $
//  
//  $Revision: #1 $
//  
//  $Change: 781912 $
//  
//  Copyright 1997-2010 Adobe Systems Incorporated. All rights reserved.
//  
//  NOTICE:  Adobe permits you to use, modify, and distribute this file in accordance 
//  with the terms of the Adobe license agreement accompanying it.  If you have received
//  this file from a source other than Adobe, then your use, modification, or 
//  distribution of it requires the prior written permission of Adobe.
//  
//========================================================================================

#include "VCPlugInHeaders.h"

// interface includes
#include "IIdleTaskMgr.h"

// General includes:
#include "CIdleTask.h"

// Project includes
#include "AMPID.h"
#include <iostream>
#include "JSONHelper.h"
#include "HTTPRequestHelper.h"
#include "ISelectionUtils.h"
#include "AMPLogDataRecord.h"
//#include "Notifier.h"
#include "AMGlobal.h"
#include "AMPCAlert.h"
//#include "AMPDocument.h"

//const static int kPnlTrvExecInterval = 10*1000; // 10 seconds, as we specify milliseconds between checks	
const static int kPnlTrvExecInterval = 180*1000; // 3 minutes, as we specify milliseconds between checks	
// Refresh  in case we add new images


/** Implements IIdleTask, to refresh the view onto the file system.
	Just lets us keep up to date when people add new assets.
	This implementation isn't too respectful; it just clears the tree and calls ChangeRoot.

	
	@ingroup paneltreeview
*/
class AMPIssueIdleTask : public CIdleTask
{
public:

	/**	Constructor
		@param boss boss object on which this interface is aggregated
	*/
	AMPIssueIdleTask(IPMUnknown* boss);

	/**	Destructor
	*/
	virtual ~AMPIssueIdleTask() {}


	/**	Called by the idle task manager in the app core when the task is running
		@param appFlags [IN] specifies set of flags which task can check to see if it should do something
			this time round
		@param timeCheck [IN] specifies how many milliseconds before the next active task becomes overdue.
		@return uint32 giving the interval (msec) that should elapse before calling this back
	 */
	virtual uint32 RunTask(uint32 appFlags, IdleTimer* timeCheck);

	/**	Get name of task
		@return const char* name of task
	 */
	virtual const char* TaskName();
	
	virtual void refresh();

	virtual void UpdateLogfile();
protected:

	/**	Update the treeview.
	 */
//	static void *GetIssueList(void* threadid);
	
	static bool ReSetTimeOutConnection();
	
	static void ExportIDML();
};

/* CREATE_PMINTERFACE
 Binds the C++ implementation class onto its ImplementationID 
 making the C++ code callable by the application.
*/
CREATE_PMINTERFACE(AMPIssueIdleTask, kAMPIssueIdleTaskImpl)


/* Constructor
*/
AMPIssueIdleTask::AMPIssueIdleTask(IPMUnknown *boss)
	:CIdleTask(boss)
{
}


/* RunTask
*/
uint32 AMPIssueIdleTask::RunTask(
	uint32 appFlags, IdleTimer* timeCheck)
{
	if( appFlags & 
		( IIdleTaskMgr::kMouseTracking 
		| IIdleTaskMgr::kUserActive 
		| IIdleTaskMgr::kInBackground 
		| IIdleTaskMgr::kMenuUp))
	{
		return kOnFlagChange;
	}
	
	//if(g_IsIssueEnable == TRUE)
	//{
		////cout << "AMPIssueIdleTask this value: " << this << endl;
		//this->refresh();
	//}
	bool returnCode = FALSE;
	// Toan modified here
	n_mSessionCounterReset++;		// After 3 mins
	////cout << "After 3 mins" << endl;
	if((n_mSessionCounterReset >= n_mSessionTotalCounterReset) && (g_IsLoggedIn == TRUE))
	{
		//Request CMS to reset timeout connection
		returnCode = this->ReSetTimeOutConnection();
		if(returnCode == TRUE)
		{
			SaveSessionInfo();
			//SaveLogHeaderFile();
		}
	}
	//this->ExportIDML();
	//AMPUtils::StoryInfoHiddenSetting();
	// Has FS changed?
	return kPnlTrvExecInterval;
}


/* TaskName
*/
const char* AMPIssueIdleTask::TaskName()
{
	return kAMPIssueIdleTaskKey;
}


/* refresh
*/
void AMPIssueIdleTask::refresh()
{
	//cout << "AMPIssueIdleTask::refresh() " << endl;
	
	do {
		////cout << "refresh after 10s" << endl;
		string api_prefix = API_PREFIX;
		string content = HTTPRequestHelper::getDataFromURL(g_Domain + "/" + api_prefix+"/magazines");
		JSONHelper::initMagazines(content);
		int fraction = 70 / g_Magazine_Count;
		////cout << "fraction " << fraction << endl;
		for (int i = 0; i < g_Magazine_Count; i++) {
			//g_Magazines[i]._issueSize = 0;	
			string issueURL = g_Domain + "/" + api_prefix + "/magazines/" + g_Magazines[i]._id;
			string issueContent = HTTPRequestHelper::getDataFromURL(issueURL);
			JSONHelper::fillMagazine(i, issueContent, FALSE);
			//b_SystemWait = TRUE;	
			
			////cout << "=====issueContent: " << issueContent << endl;
		}
		
		
	
		// redraw UI
		//InterfacePtr<ITreeViewMgr> treeMgr(treeWidget, UseDefaultIID());
		////cout << "redraw UI" << endl;
		//Notifier *notifier = Notifier::GetInstance();
		//notifier->Notify();
		////cout << "end +++++++++++++++" << endl;
		
	} while(false);
	
	/*
	pthread_t threads[1];
	int threadID = 1;
	int rc = pthread_create(&threads[0], NULL, AMPIssueIdleTask::GetIssueList, NULL);
	
	if (rc) {
		//cout << "Error: unable to create thread" << rc << endl;
		return;
	}
	//pthread_exit(NULL);
	 */
}


void AMPIssueIdleTask::UpdateLogfile()
{
	SaveLogHeaderFile();
}

/*
void *AMPIssueIdleTask::GetIssueList(void *threadid) {
	////cout << "refresh after 10s" << endl;
	do {
		string api_prefix = API_PREFIX;
		string content = HTTPRequestHelper::getDataFromURL(g_Domain + "/" + api_prefix+"/magazines");
		//JSONHelper::initMagazines(content);
		for (int i = 0; i < g_Magazine_Count; i++) {
			
			string issueURL = g_Domain + "/" + api_prefix + "/magazines/" + g_Magazines[i]._id;
			string issueContent = HTTPRequestHelper::getDataFromURL(issueURL);
			//JSONHelper::fillMagazine(i, issueContent);
			//b_SystemWait = TRUE;	
			
			////cout << "=====issueContent: " << issueContent << endl;
		}
		
		// redraw UI
		//cout << "downloaded done, post notification" << endl;
		//Notifier *notifier = Notifier::GetInstance();
		//notifier->Notify();
		//cout << "end +++++++++++++++" << endl;
		
	} while(false);
	//pthread_exit(NULL);

}
*/

bool AMPIssueIdleTask::ReSetTimeOutConnection()
{
	int returnCode = FALSE;
	////cout << "Reset time connection" << endl;
	//int32 totaltime = (n_mSessionCounterReset * 10);
	int32 totaltime = (n_mSessionCounterReset * 180);
	returnCode = HTTPRequestHelper::RequestSession();
	if(returnCode == -1)
	{
		//This package will be invalid to use
		AMPCAlert::ModalAlert
		(
		 PMString("File open on another computer by same user.\n\nThis user session has now closed."),		// Alert string
		 PMString("Yes"),				// OK button
		 kNullString,					// Cancel button
		 kNullString, 					// No third button
		 kNoNeedToWaitForDialog,		// Set OK button to default
		 1								// No icon.
		 );
		// Clean up
		AMPUtils::ClearAllFile();
		AMPUtils::ClearPackageAndSessionInfo();
		AMPUtils::ClearUserInfo();
		AMPUtils::RefreshMainPanel(FALSE);
		return FALSE;
	} 
	else if(returnCode == TRUE)
	{
		// request new session for stories
		for (int i = 0; i < g_TextFrameCount; i++) {
			if (g_TextFrames[i].isLocked == TRUE) {
				returnCode = HTTPRequestHelper::RequestStorySession(g_TextFrames[i].sessionID);
			}
		}
		
		if(returnCode == TRUE)
		{
			n_mSessionCounterReset = 0;
		}
	}
	//else if ((totaltime >= n_mSessionTimeOut) && (g_IsCheckOut == TRUE))		// Beyond the specified time
	else if ((totaltime >= n_mSessionTimeOut) && g_DocName.length() > 0)		// Beyond the specified time
	{
		int16 result = AMPCAlert::ModalAlert
		(
		 PMString("InDesign can not connect to server.\n\nCheck your internet connect and try again."),		// Alert string
		 PMString("Yes"),				// OK button
		 PMString("No"), 				// Cancel button
		 kNullString, 					// No third button
		 kNeedToWaitForDialog,			// Set kNeedToWaitForDialog to default
		 1								// No icon.
		 );
		if (result == kOKSystem)
		{
			// recall again
			return ReSetTimeOutConnection();
		}else
		{
			n_mSessionCounterReset = 0;
		}
	}
	
	return returnCode;
}
/*
void AMPIssueIdleTask::ExportIDML() {
	//cout << "auto export idml" << endl;
	if(Utils<ILayoutUIUtils>() == nil)
	{
		return;
	}
	IDocument* document = Utils<ILayoutUIUtils>()->GetFrontDocument();
	// +precondition
	ASSERT(document);
	if(!document) {
		//cout << "Cannot load document" << endl;
		return;
	}
	PMString docName; 
	document->GetName(docName);
	////cout << "TraceBoss docName: " << docName.GrabCString() << endl;
	string nameStr = docName.GrabCString();
	UIDRef docRef = GetUIDRef(document); 

	if (g_DocName.length() > 0 && g_DocName.compare(nameStr) == 0) {
		
		//string IDMLexport = g_SDK_WorkspaceDir + ":" + g_IDMLOpen + ".idml";
		string IDMLexport = g_SDK_WorkspaceDir + ":" + g_Package_id + ".idml";
		//string JPEGexport = g_SDK_WorkspaceDir + ":" + g_Pageid +".jpg";
		
		PMString fileLocation(IDMLexport.c_str());
		IDFile sysIDMLFile(fileLocation);
		
		//fileLocation = PMString(JPEGexport.c_str());
		IDFile sysJPEGFile(fileLocation);
		
		bool shouldExport = FALSE;
		shouldExport = AMPUtils::SetIDToTextFrame(docRef);	
		if (shouldExport == TRUE) {
			//AMPDocument::exportJPEGFile(docRef, sysJPEGFile, FALSE);
		//	AMPDocument::DoIDMLFileCreating(docRef, sysIDMLFile, FALSE);
			AMPUtils::GetIDFromTextFrame(docRef);
		}
	}
}
*/
//	end, File:	AMPIssueIdleTask.cpp
